package org.example.aitest.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;
import org.example.aitest.dto.EHL;
import org.example.aitest.utils.gen.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/file")
@Api(tags = "文件操作")
public class FileController {

    @Autowired
    public ExcelUtil excelUtil;

    /**
     * 自动根据excel创建表并将数据添加
     * */
    @ApiOperation(value = "上传文件",notes = "根据上传excel文件生成对应数据库和项目结构")
    @PostMapping("/exGen")
    public String exGen(@ApiParam(value = "上传的文件",required = true) @RequestPart MultipartFile file){
        excelUtil.createTableToExcel(file);
        return "success";
    }

    /**
     * @description: TODO 比较上传的两个excel文件的差异
     * @author zb
     * @date 2025/8/22
     * @version: 1.0
    */
    @PostMapping("/oct")
    public void oct(HttpServletResponse response,@RequestPart(value = "oldFile") MultipartFile oldFile,@RequestPart(value = "newFile") MultipartFile newFile,
                    @RequestParam(required = false) Integer sl,@RequestParam(required = false) Integer rl) throws IOException {

        // 设置响应头
        setResponseHeaders(response, newFile.getOriginalFilename());
        OutputStream outputStream = response.getOutputStream();

        List<EHL> list = null;
        if(rl == null || rl < 0) {
            list = ExcelUtil.oct(oldFile, newFile, sl,-1);
        }else {
            list = ExcelUtil.oct(oldFile,newFile,sl,rl);
        }

        String oldName = oldFile.getOriginalFilename();
        String newName = newFile.getOriginalFilename();
        String oldLa = oldName.substring(oldName.lastIndexOf(".") + 1);
        String newLa = newName.substring(newName.lastIndexOf(".") + 1);

        if(newLa.equals("xlsx")) {
            XSSFWorkbook newExcel = new XSSFWorkbook(newFile.getInputStream());
            //暂定只比较一张表
            XSSFSheet newSheet = newExcel.getSheetAt(0);
            //将newFile对应list中的行列做标记
            for (int i = 0; i < list.size(); i++) {
                EHL ehl = list.get(i);
                XSSFRow row = newSheet.getRow(ehl.getH());
                XSSFCell cell = row.getCell(ehl.getL());

                //创建或获取单元格样式
                XSSFCellStyle style = newExcel.createCellStyle();
                style.cloneStyleFrom(cell.getCellStyle());

                // 设置背景色为红色
                style.setFillForegroundColor(IndexedColors.RED.getIndex());
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                cell.setCellStyle(style);
            }

            newExcel.write(outputStream);
            outputStream.flush();
        } else if (newLa.equals("xls")) {
            HSSFWorkbook newExcel = new HSSFWorkbook(newFile.getInputStream());
            //暂定只比较一张表
            HSSFSheet newSheet = newExcel.getSheetAt(0);
            //将newFile对应list中的行列做标记
            for (int i = 0; i < list.size(); i++) {
                EHL ehl = list.get(i);
                HSSFRow row = newSheet.getRow(ehl.getH());
                HSSFCell cell = row.getCell(ehl.getL());

                //创建或获取单元格样式
                HSSFCellStyle style = newExcel.createCellStyle();
                style.cloneStyleFrom(cell.getCellStyle());

                // 设置背景色为红色
                style.setFillForegroundColor(IndexedColors.RED.getIndex());
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                cell.setCellStyle(style);
            }

            newExcel.write(outputStream);
            outputStream.flush();
        }
    }

    /**
     * 设置HTTP响应头
     */
    private void setResponseHeaders(HttpServletResponse response, String originalFilename) {
        String encodedFilename = URLEncoder.encode(originalFilename, StandardCharsets.UTF_8)
                .replaceAll("\\+", "%20");

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=newFile.xlsx");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
    }
}
